<template>
  <div class="inventory-form" style="width: 1200px; margin: 0 auto">
    <h3 style="margin-bottom: 20px">新增盘点单</h3>
    <el-form :model="form" label-width="120px">
      <el-row>
        <el-col span="12">
          <el-form-item label="盘点单号">
            <el-input
              disabled
              v-model="form.stockNum"
              placeholder="可不填写，自动生成"
            ></el-input>
            <el-input
              disabled
              v-model="form.stockNum"
              placeholder="可不填写，自动生成"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col span="12">
          <el-form-item label="关联订单号">
            <el-input
              v-model="form.internalCode"
              placeholder="请填写关联订单号"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col span="12">
          <el-form-item label="制单人">
            <el-input v-model="form.stock" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col span="12">
          <el-form-item label="制单时间">
            <el-date-picker
              v-model="form.relaCreationTime"
              type="date"
              placeholder="2019-05-25"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-col :span="12">
        <el-form-item label="单据类型" required>
          <el-select
            v-model="form.relaReviewer"
            placeholder="请选择"
            class="form-select" >
            <el-option label="等待审核" value="等待审核"></el-option>
            <el-option label="审核成功" value="审核成功"></el-option>
            <el-option label="审核失败" value="审核失败"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    
      <el-form-item label="备注">
        <el-input
          type="textarea"
          v-model="form.Rember"
          :maxlength="300"
          placeholder="请输入备注信息"
          show-word-limit
        ></el-input>
      </el-form-item>
    </el-form>
    <h4 style="margin: 20px 0">产品信息</h4>
    <div style="display: flex; justify-content: flex-end; margin-bottom: 10px">
      <el-button
        type="primary"
        @click="openProductSelector"
        class="action-button"
        >新增产品</el-button
      >
    </div>
    <el-table :data="productList" border class="product-table">
      <el-table-column label="产品编码" prop="productId"></el-table-column>
      <el-table-column label="产品名称" prop="productName"></el-table-column>
      <el-table-column label="规格" prop="specification"></el-table-column>
      <!-- <el-table-column label="存储单位" prop="unitId"></el-table-column> -->

      <!-- 新增批次列，可根据实际需求决定是否展示/编辑 -->
      <el-table-column label="批次">
        <template #default="scope">
          <el-input
            v-model="scope.row.batch"
            placeholder="输入批次"
            type="number"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="库位" prop="storageLocationId"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            type="text"
            @click="deleteProduct(scope.row)"
            class="table-ops-button"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="button-group" style="margin-top: 20px">
      <el-button type="primary" @click="submitForm" style="margin-right: 10px"
        >提交</el-button
      >
      <el-button @click="resetForm">取消</el-button>
    </div>
  </div>
  <el-dialog
    title="选择产品"
    ref="dialogRef"
    v-model="dialogVisible"
    width="1200px"
  >
    <el-form :model="searchParams" class="search-form">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="产品编号">
            <el-input
              v-model="searchParams.productCode"
              placeholder="请输入编码"
              class="form-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品名称">
            <el-input
              v-model="searchParams.productName"
              placeholder="请输入名称"
              class="form-input"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="search-button-container">
      <el-button type="primary" @click="searchProducts" class="search-button">
        搜索
      </el-button>
    </div>
    <br />
    <el-table
      @selection-change="handleSelectionChange"
      :data="dialogProductList"
      border
      class="product-table"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="产品编码" prop="productId"></el-table-column>
      <el-table-column label="产品名称" prop="productName"></el-table-column>
      <el-table-column label="规格" prop="specification"></el-table-column>
      <el-table-column label="类别" prop="category"></el-table-column>
      <el-table-column label="单价" prop="price"></el-table-column>
      <el-table-column label="显示名" prop="description"></el-table-column>
    </el-table>
    <br />
    <el-pagination
      v-model:current-page="form1.PageIndex"
      v-model:page-size="form1.PageSize"
      :page-sizes="[1, 3, 15, 100]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="form1.TotalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <br />
    <div class="button-group">
      <el-button @click="closeDialog" class="action-button"> 关闭 </el-button>
      <el-button type="primary" @click="confirmSelection" class="action-button">
        选择
      </el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessageBox, ElMessage } from "element-plus";
import { reactive, onMounted, ref } from "vue";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import dayjs from "dayjs";
import { KongaUrl } from "@/axios/axiosHelp";
const generateTwelveDigitNumber = () => {
  const characters = "0123456789";
  let result = "";
  for (let i = 0; i < 12; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
};

onMounted(() => {
  form.value.stockNum = generateTwelveDigitNumber();
});

const form1 = reactive({
  TotalCount: 0,
  PageCount: 0,
  PageSize: 5,
  PageIndex: 1,
});


const handleSizeChange = (newSize:any) => {
  form1.PageSize = newSize;
  searchProducts();
};

const handleCurrentChange = (newPage:any) => {
  form1.PageIndex = newPage;
  searchProducts();
};



const openProductSelector = () => {
  dialogVisible.value = true;
  searchProducts();
};
const productList = ref([]);
const dialogProductList = ref([]);

const dialogVisible = ref(false);
const searchProducts = () => {
  KongaUrl
    .get("/wangcong/api/Whouase/GetProductModels", {
      params: {
        PageSize: form1.PageSize,
        PageIndex: form1.PageIndex,
      },
    })
    .then((res) => {
      dialogProductList.value = res.data.data.list;
      form1.TotalCount = res.data.data.totalCount;
      form1.PageCount = res.data.data.PageCount;
    })
    .catch((error) => {
      console.error("获取产品列表失败", error);
    });
};
const deleteProduct = (product) => {
  ElMessageBox.confirm("确定要删除该产品吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const index = productList.value.indexOf(product);
      if (index !== -1) {
        productList.value.splice(index, 1);
      }
    })
    .catch(() => {});
};

const dialogSelection = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  dialogSelection.value = val;
};
const confirmSelection = () => {
  const selectedRows = dialogSelection.value;
  if (selectedRows.length === 0) {
    ElMessage.warning("请选择产品");
    return;
  }
  selectedRows.forEach((selectedProduct) => {
    productList.value.push({
      pRelatuionshipName: selectedProduct.pRelatuionshipName,
      seadId: selectedProduct.seadId,
      storageLocationId: selectedProduct.storageLocationId,
      batch: selectedProduct.batch,
      pRelatuionshipGuige: selectedProduct.pRelatuionshipGuige,
      pRelatuionshipId: selectedProduct.pRelatuionshipId,
      pRelatNumber: selectedProduct.pRelatNumber,
    });
  });
  closeDialog();
};
const calculateTotal = (row: any) => {
  if (row.quantity !== "" && row.pRelatuionshipPrice !== "") {
    row.totQuantity = (
      Number(row.quantity) * Number(row.pRelatuionshipPrice)
    ).toFixed(2);
  } else {
    row.totQuantity = "";
  }
};
const searchParams = ref({
  productCode: "",
  productName: "",
});
const closeDialog = () => {
  dialogVisible.value = false;
  searchParams.value.productCode = "";
  searchParams.value.productName = "";
  dialogProductList.value.forEach((row) => {
    row._checked = false;
  });
};

// 产品数据
const products = ref([]);


// 表单数据
const form = ref({
  stock: "陈平安",
  relaCreationTime: dayjs().format("YYYY-MM-DD"), // 格式化日期时间,
  Rember: "",
  stockNum: "",
  internalCode: "",
  relaReviewer: "",
  StocktakingModelId: 0,
});
// 提交表单
const submitForm = async () => {
  // 检查产品列表是否为空
  if (productList.value.length === 0) {
    ElMessage.warning("请至少选择一个产品");
    return;
  }

  // 检查产品编码是否为空
  const invalidProducts = productList.value.filter(
    (product) => !product.productId
  );
  if (invalidProducts.length > 0) {
    ElMessage.error("产品编码不能为空");
    return;
  }

  // 组装请求体，确保字段完整且与后端匹配
  const stocktakingCommand = {
    // StocktakingModel: {
    //   StockNum: form.value.stockNum, // 前端生成的盘点单号
    //   Relatedorders: form.value.relatedorders, // 前端生成的关联订单号
    //   RelaCreator: form.value.maker, // 制单人
    //   RelaCreationTime: form.value.makeTime, // 制单时间
    //   Rember: form.value.remark, // 备注
    //   IsDelete: 0, // 假设默认未删除
    // },
    ...form.value,
    Products: productList.value.map((product) => ({
      ProductId: product.productId,
      StockNum: form.value.stockNum,
      // 产品编码，确保后端能接收
      // 若后端还有其他必填字段（如 Quantity、Batch 等），需补充完整
      // Quantity: product.quantity, // 示例：若后端需要数量，从表格获取
      // Batch: product.batch, // 示例：若后端需要批次，从表格获取
    })),
  };

  try {
    const response = await KongaUrl.post(
      "/wangcong1/api/WHouase/AddStocktaking",
      stocktakingCommand
    );
    if (response.data.code === 200) {
      ElMessage.success("添加成功");
      // 重置表单
      productList.value = [];
    } else {
      ElMessage.error(`添加失败: ${response.data.message}`);
    }
  } catch (error) {
    console.error("提交表单失败", error);
    ElMessage.error("提交表单时发生错误，请检查网络或联系管理员");
  }
};

// 重置表单
const resetForm = () => {
  productList.value = [];
};
</script>

<style scoped>
.inventory-form {
  padding: 20px;
  box-sizing: border-box;
}
.button-group {
  text-align: center;
}
.el-table__header th {
  text-align: center;
}
.el-table__body td {
  text-align: center;
}
</style>